package com.nil.codegen.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

@Slf4j
public class FileUtil {


    /**
     * 创建文件并写入内容
     */
    public static String createFile(byte[] bytes, String fileName, String path) {

        File dir = new File(path);
        if (!dir.isDirectory()) {
            log.error("目录非法");
        }
        if (!dir.exists()) {
            boolean mk = dir.mkdir();
            if (mk) {
                log.info("目录创建成功");
            }
        }

        String fileFullPath = path + File.separator + fileName;
        File file = new File(fileFullPath);
        try (FileOutputStream fos = new FileOutputStream(file)) {
            fos.write(bytes);
            fos.flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return fileFullPath;
    }


    /**
     * 根据当前时间戳 年月日时 创建目录
     */
    public static String mkDirByTimestamp(String parentPath) {
        DateFormat sdf = new SimpleDateFormat("yyyyMMddHH");
        String timestamp = sdf.format(new Date());
        String dirPath = parentPath + File.separator + timestamp;
        File dir = new File(dirPath);
        if (!dir.exists()) {
            boolean mkdir = dir.mkdirs();
            if (!mkdir) {
                log.error("目录创建失败 {}", dirPath);
            }
        }

        return dirPath;
    }


    /**
     * @param file
     * @return
     */
    public static double getFileSize2KB(MultipartFile file) {
        long size = file.getSize();
        return new BigDecimal(size / 1024.0)
                .setScale(2, RoundingMode.HALF_UP)
                .doubleValue();
    }


    /**
     *  下载文件
     * @param response   HttpServletResponse
     * @param fileName  下载的文件名 (可以与原始文件名不一样)
     * @param file      下载的文件
     */
    public static void download(HttpServletResponse response, String fileName, File file) {
        try {
            String title = URLEncoder.encode(fileName, "UTF-8");
            response.reset();
            response.setContentType("application/octet-stream");
            response.setCharacterEncoding("utf-8");
            response.setContentLength((int) file.length());
            response.setHeader("Content-Disposition", "attachment;filename=" + title + ";" + "filename*=utf-8''" + title);
            // 放行Content-disposition响应头
            response.setHeader("Access-Control-Expose-Headers", "Content-disposition");
            response.setHeader("Access-Control-Allow-Origin", "*");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e.getMessage());
        }

        try (BufferedInputStream bis = new BufferedInputStream(Files.newInputStream(file.toPath())); OutputStream os = response.getOutputStream()) {
            byte[] buff = new byte[1024];
            int i = 0;
            while ((i = bis.read(buff)) > 0) {
                os.write(buff, 0, i);
            }
            os.flush();

        } catch (IOException e) {
            throw new RuntimeException(e.getMessage());
        }
    }


}
